package handle;

import com.google.common.collect.ImmutableMap;
import common.pojo.CommonResult;
import common.utils.JsonUtils;
import httpclient.HttpClientUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;
import pojo.ChatRecord;
import pojo.MessageModel;
import pojo.UserShopInfo;
import pojo.form.ChatRecordAddForm;
import service.ChatAopService;
import service.ChatRecordService;
import service.cfg.ShopCfg;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 用户信息应存在其他地方。。。。。WebSocketSession不可序列化，无法存储redis
 */
@Service
public class WebSocketPushHandler implements WebSocketHandler {
    @Autowired
    ChatAopService chatAopService;
    @Autowired
    ChatRecordService chatRecordService;

    @Autowired
    ShopCfg shopCfg;
    //   private static final List<WebSocketSession> users = new ArrayList<>();
    //记录活跃用户
    private static final Map<String, WebSocketSession> user = new HashMap<>();
    //店主活跃标识
    private static final Map<String, WebSocketSession> shopUser = new HashMap<>();
    //    //记录所有人信息，发送消息的时候直接取map里面的WebSocketSession，唯一标识key为 WebSocketSession.id
//    private static final Map<String,WebSocketSession> maps = new HashMap<>();
    //店铺id
    private static final String SHOPID = "shopId";
    //wxUserId
    private static final String CUSTOMEID = "customId";

    private static final String ISSHOP = "isShop";

    private final Logger LOG = LoggerFactory.getLogger(WebSocketPushHandler.class);

    // 用户进入系统监听
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String shopId = webSocketSession.getAttributes().get(SHOPID).toString();
        String customId = webSocketSession.getAttributes().get(CUSTOMEID).toString();
        String isShop = webSocketSession.getAttributes().get(ISSHOP).toString();
        Map map = new HashMap();
        if ("Y".equals(isShop)) {
            if(StringUtils.isBlank(shopId)){
                map.put("type", "error");
            }else {
                shopUser.put(shopId, webSocketSession);
            }

        } else {
            if(StringUtils.isBlank(shopId)){
                map.put("type", "error");
            }else {
                user.put(customId, webSocketSession);
            }
        }
        map.put("type", "login");
        sendMessageToUser(webSocketSession, new TextMessage(JsonUtils.toJson(map)));

    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        String shopId = webSocketSession.getAttributes().get(SHOPID).toString();
        String customId = webSocketSession.getAttributes().get(CUSTOMEID).toString();
        String isShop = webSocketSession.getAttributes().get(ISSHOP).toString();
        if ("Y".equals(isShop)) {
            webSocketSession.getAttributes().put("isRead", "Y");
            //是店主发送过来的消息 //接收人customId
            if (user.containsKey(customId)) {
                sendMessageToUser(user.get(customId), new TextMessage(webSocketMessage.getPayload().toString()));
                webSocketSession.getAttributes().put("isSend", "N");
            }else {
                webSocketSession.getAttributes().put("isSend", "Y");
            }
        } else {
            webSocketSession.getAttributes().put("isSend", "N");
            if (shopUser.containsKey(shopId)) {
                webSocketSession.getAttributes().put("isRead", "Y");
                sendMessageToUser(shopUser.get(shopId), new TextMessage(webSocketMessage.getPayload().toString()));
            } else {
                webSocketSession.getAttributes().put("isRead", "N");
            }
        }
        if (webSocketSession.isOpen()) {
            webSocketSession.sendMessage(new TextMessage(webSocketMessage.getPayload().toString()));
        }
    }

    // 后台错误信息处理方法
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if (webSocketSession.isOpen()) {
            Map map = new HashMap();
            map.put("type", "error");
            webSocketSession.sendMessage(new TextMessage(JsonUtils.toJson(map)));
        }
    }

    // 用户退出后的处理，不如退出之后，要将用户信息从websocket的session中remove掉，这样用户就处于离线状态了，也不会占用系统资源
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        if (webSocketSession.isOpen()) {
            webSocketSession.close();
        }
        String shopId = webSocketSession.getAttributes().get(SHOPID).toString();
        String customId = webSocketSession.getAttributes().get(CUSTOMEID).toString();
        String isShop = webSocketSession.getAttributes().get(ISSHOP).toString();
        if ("Y".equals(isShop)) {
            shopUser.remove(shopId);
        } else {
            user.remove(customId);
        }
        System.out.println("安全退出了系统");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }


    /**
     * 给所有的用户发送消息
     */
    public void sendMessagesToUsers(WebSocketSession ebSocketSession) {
//        for(WebSocketEum eum:users){
//            if(eum.getWebSocketSession().isOpen()){
//                try {
//                    eum.getWebSocketSession().sendMessage(message);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    System.out.println(e);
//                }
//            }
//        }
    }


    /**
     * 发送消息给指定的用户
     */
    public void sendMessageToUser(WebSocketSession session, TextMessage message) {
        if (session.isOpen()) {
            try {
                session.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                LOG.warn("---------消息转发失败---sendMessageToUser----");
            }
        }
    }


    public  CommonResult sendMsg(Long shopId, Long customId, String msg) {
        //是店主发送过来的消息 //接收人customId
        CommonResult commonResult = HttpClientUtils.get(shopCfg.getShopInfoDetail(), ImmutableMap.of("shopId", shopId));
        UserShopInfo shopInfo = JsonUtils.objectToPojo(commonResult.getData(), UserShopInfo.class);
        if(shopInfo==null){
            return CommonResult.returnFailsWrapper("此店主信息不存在");
        }
        ChatRecord record = chatRecordService.getChatRecord(customId, shopId);
        MessageModel model = new MessageModel();
        if(record==null){
            model.setId("msg" + 1);
        }else {
            model.setId("msg" + record.getId());
        }

        model.setCustomId(customId);
        model.setMessage(msg);
        model.setIsShop("true");
        model.setUrl(shopInfo.getLogo());

        if (user.containsKey(customId.toString())) {
            sendMessageToUser(user.get(customId.toString()), new TextMessage(JsonUtils.toJson(model)));
            if(shopUser.containsKey(shopId.toString())){
                 sendMessageToUser(shopUser.get(shopId.toString()), new TextMessage(JsonUtils.toJson(model)));
             }
            ChatRecordAddForm addForm = new ChatRecordAddForm(JsonUtils.toJson(model),shopInfo.getLogo(),"Y",shopId,new Date(),customId);
            chatAopService.addChatRecord(addForm);
            return CommonResult.returnDataWrapper("发送成功");
        }else {
            ChatRecordAddForm addForm = new ChatRecordAddForm(JsonUtils.toJson(model),shopInfo.getLogo(),"Y",shopId,new Date(),customId);
            chatAopService.addChatRecord(addForm);
            if(shopUser.containsKey(shopId.toString())){
                sendMessageToUser(shopUser.get(shopId.toString()), new TextMessage(JsonUtils.toJson(model)));
            }
            return CommonResult.returnDataWrapper("用户已下线,已转为离线消息");
        }
    }

}
